import { _decorator, Component, Node } from 'cc';

import {GameMain} from "./GameMain";

export class GameOper extends Component
{
    //是否可操作
    public _canOper:boolean=false;

    public pressed:boolean=false;
    //public pressedStartGridIdx:number=-1;

    public connectedGrids:Array<number>=[];

    //本次操作得分
    public score:number=0;

    public selGrid0:number=-1;
    public selGrid1:number=-1;
    
    public static readonly connectSteps:Array<number>=[1,2,4,8,16,32,64];

    public setCanOper(canOper:boolean)
    {
        this._canOper=canOper;
    }

    public canOper():boolean
    {
        return this._canOper;
    }

    public reset()
    {
        this.pressed=false;
        //this.pressedStartGridIdx=-1;
        this.clearConnectedGrids();
        this.score=0;
    }

    public resetSelGrid()
    {
        this.selGrid0=-1;
        this.selGrid1=-1;
    }

    public getSelGrid0():number
    {
        return this.selGrid0;
    }

    public setSelGrid0(gridIdx:number)
    {
        this.selGrid0=gridIdx;
    }

    public getSelGrid1():number
    {
        return this.selGrid1;
    }

    public setSelGrid1(gridIdx:number)
    {
        this.selGrid1=gridIdx;
    }

    public clearConnectedGrids()
    {
        this.connectedGrids.splice(0, this.connectedGrids.length);
    }

    public addConnectedGridIdx(idx:number)
    {
        for(let i=0;i<this.connectedGrids.length;i++)
        {
            if(this.connectedGrids[i]===idx)
            {
                console.error("*** Error 重复的connected grid id idx="+i);
            }
        }
        this.connectedGrids.push(idx);

        this.calcScore();
    }

    public getConnectedGridsCount():number
    {
        return this.connectedGrids.length;
    }

    public calcScore()
    {
        if(this.connectedGrids.length<=1)
        {
            this.score=0;
            return;
        }

        let score:number=0;
        this.score=score;
    }

    public setPressed(pressed:boolean)
    {
        this.pressed=pressed;
    }

    public isPressed():boolean
    {
        return this.pressed;
    }

    public getPressedStartGridIdx():number
    {
        if(this.connectedGrids.length>0)
            return this.connectedGrids[0];
        return -1;
    }

    public isInConnectedList(gridIdx:number):boolean
    {
        for(let i=0;i<this.connectedGrids.length;i++)
        {
            if(this.connectedGrids[i]===gridIdx)
            {
                return true;
            }
        }
        return false;
    }

    public removeLastConnectedGrid()
    {
        if(this.connectedGrids.length>0)
        {
            let idx:number=this.connectedGrids.pop();
            GameMain.instance.grids[idx].onRelease();
            this.score /=2;
            if(this.connectedGrids.length===0)
                this.score=0;
        }

        this.calcScore();
    }
}












